<template>
  <div class="dropdown" ref="dropdownRef">
    <a @click.prevent="toggleOpen" class="btn btn-outline-light dropdown-toggle" type="button">
      {{ title }}
    </a>
    <ul v-if="isOpen" class="dropdown-menu" :style="{ display: 'block' }">
      <slot></slot>
    </ul>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, onUnmounted, ref, watch } from 'vue'
import { useClickOutSide } from '../hooks/useClickOutSide'

export default defineComponent({
  name: 'Dropdown',
  props: {
    title: {
      type: String,
      required: true
    }
  },
  setup () {
    const isOpen = ref(false)
    const dropdownRef = ref<null|HTMLElement>(null)
    const toggleOpen = () => {
      isOpen.value = !isOpen.value
    }

    const isOutside = useClickOutSide(dropdownRef)

    watch(isOutside, () => {
      if (isOpen.value && isOutside.value) {
        isOpen.value = false
      }
    })

    return {
      isOpen,
      toggleOpen,
      dropdownRef
    }
  }
})
</script>

<style scoped>
</style>
